package com.niji.littly_donkey_android.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.*;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.android.volley.*;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.makeramen.roundedimageview.RoundedImageView;
import com.niji.littly_donkey_android.R;
import com.niji.littly_donkey_android.bean.JsonBean;
import com.niji.littly_donkey_android.http.*;
import com.niji.littly_donkey_android.util.*;
import com.niji.littly_donkey_android.view.CircleImageView;
import com.xuexiang.xui.widget.picker.widget.OptionsPickerView;
import com.xuexiang.xui.widget.picker.widget.builder.OptionsPickerBuilder;
import com.xuexiang.xui.widget.picker.widget.listener.OnOptionsSelectListener;
import okhttp3.*;
import org.json.JSONArray;
import org.json.JSONException;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class UpdateInfoActivity extends BaseActivity {

    private static final String TAG = "UpdateInfoActivity";

    /**
     * 输入框初始值
     */
    private int num = 0;

    /**
     * 输入框最大值
     */
    private int maxNum = 80;

    /**
     * 输入框内容
     */
    private EditText update_info_avatar;

    /**
     * 显示实施数字
     */
    private TextView update_info_avaNum;

    private Button update_info_return;

    /**
     * 选择城市
     */
    private TextView update_info_select_city;

    /***
     * 修改头像
     */
    private RoundedImageView update_info_head;

    private EditText update_info_nickname;

    private EditText update_info_sex;

    private EditText update_info_age;

    private TextView update_info_id;

    private RelativeLayout update_info_main;

    private RelativeLayout update_info_loading;

    private Button update_info_btn;

    private Thread thread;

    private static String photoPath = null;

    private static final int REQUEST_WRITE_EXTERNAL_STORAGE = 1;
    private static final int CHOOSE_PHOTO = 2;

    private List<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();

    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;
    private static boolean isLoaded = false;


    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.update_info);
        init();
        updateInfoReturn();
        selectCity();
        UpdateInfoInput();
        updateInfoBtn();

    }


    @Override
    protected int getLayoutId() {
        return R.layout.update_info;

    }

    @Override
    protected int getStatusBarColor() {
        return R.color.white_easy_photos;
    }

    private void init() {
        update_info_nickname = findViewById(R.id.update_info_nickname);
        update_info_sex = findViewById(R.id.update_info_sex);
        update_info_age = findViewById(R.id.update_info_age);
        update_info_id = findViewById(R.id.update_info_id);
        update_info_select_city = findViewById(R.id.update_info_select_city);
        update_info_head = findViewById(R.id.update_info_head);
        update_info_avaNum = findViewById(R.id.update_info_avaNum);
        thread = new Thread(new Runnable() {
            @Override
            public void run() {
                // 子线程中解析省市区数据
                initJsonData();
            }
        });
        thread.start();

        //用户信息显示
        String url = UrlUtil.URL + "/user/user/info";
        RequestQueue requestQueue = Volley.newRequestQueue(UpdateInfoActivity.this);
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                try {
                    Map<String, Object> map = JsonUtil.jsonToMap(s);
                    Integer code = (Integer) map.get("code");
                    if (code == 0) {
                        Map<String, Object> dataMap = (Map) map.get("data");
                        Log.i(TAG, dataMap.toString());
                        Integer id = (Integer) dataMap.get("id");
                        String nickname = (String) dataMap.get("nickname");
                        String avatar = (String) dataMap.get("avatar");
                        Integer sex = (Integer) dataMap.get("sex");
                        Integer age = (Integer) dataMap.get("age");
                        String city = (String) dataMap.get("city");
                        String signature = (String) dataMap.get("signature");
                        int length = avatar.length();
                        update_info_avaNum.setText(length + "/80字符");

                        update_info_id.setText("" + id);
                        update_info_nickname.setText(nickname);
                        if (sex == 1) {
                            update_info_sex.setText("男");
                        } else if (sex == 2) {
                            update_info_sex.setText("女");
                        }
                        update_info_age.setText("" + age);
                        update_info_avatar.setText(signature);
                        update_info_select_city.setText(city);
                        String headUrl = UrlUtil.URL + avatar;

//                        NetworkGlideImageLoader.getInstance().displayImage((Activity) UpdateInfoActivity.this,headUrl,update_info_head,0,0);
                        update_info_loading = findViewById(R.id.update_info_loading);
                        update_info_main = findViewById(R.id.update_info_main);
                        update_info_main.setVisibility(View.VISIBLE);
                        update_info_loading.setVisibility(View.INVISIBLE);

                    } else if (code == -1) {
                        Toast.makeText(UpdateInfoActivity.this, "登录失效，请重新登录", Toast.LENGTH_LONG).show();
                        Intent intent = new Intent(UpdateInfoActivity.this, GetPhoneCodeActivity.class);
                        intent.putExtra("loginCode", "-1");
                        startActivity(intent);
                        finish();
                    } else {
                        Toast.makeText(UpdateInfoActivity.this, "用户信息获取失败", Toast.LENGTH_SHORT).show();
                        overridePendingTransition(R.anim.xpage_slide_in_left, R.anim.xpage_slide_out_right);
                        finish();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.e(TAG, volleyError.getMessage(), volleyError);
            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                String sesseionid = new ConnectViaSession(UpdateInfoActivity.this).GetSession();
                if (!sesseionid.equals("")) {
                    HashMap<String, String> headers = new HashMap<String, String>();
                    headers.put("cookie", sesseionid);
                    return headers;
                } else {
                    return super.getHeaders();
                }
            }
        };

        requestQueue.add(stringRequest);
    }


    /**
     * 从服务器取图片
     * @param url
     * @return
     */
    public static Bitmap getHttpBitmap(String url) {
        URL myFileUrl = null;
        Bitmap bitmap = null;
        try {
            myFileUrl = new URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        try {
            HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
            conn.setConnectTimeout(0);
            conn.setDoInput(true);
            conn.connect();
            InputStream is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了

                        Toast.makeText(UpdateInfoActivity.this, "Begin Parse Data", Toast.LENGTH_SHORT).show();
                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 子线程中解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;

                case MSG_LOAD_SUCCESS:
                    Toast.makeText(UpdateInfoActivity.this, "数据加载成功", Toast.LENGTH_SHORT).show();
                    isLoaded = true;
                    break;

                case MSG_LOAD_FAILED:
                    Toast.makeText(UpdateInfoActivity.this, "数据加载失败", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    private void selectCity() {
        update_info_select_city = findViewById(R.id.update_info_select_city);
        update_info_select_city.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                if (isLoaded) {
                    showPickerView();
                } else {
                    Toast.makeText(UpdateInfoActivity.this, "请等待数据加载", Toast.LENGTH_SHORT).show();
                }
            }
        });

    }


    private String sex = null;
    String nickname = null;
    String signature = null;
    String age = null;
    String city = null;
    File fs = null;



/**
 * 用户信息保存
 */

    private void saveUserInfo(){
        update_info_sex = findViewById(R.id.update_info_sex);
        update_info_nickname = findViewById(R.id.update_info_nickname);
        update_info_age = findViewById(R.id.update_info_age);
        update_info_select_city = findViewById(R.id.update_info_select_city);
        update_info_avatar = findViewById(R.id.update_info_avatar);
        sex = update_info_sex.getText().toString().trim();
        if (sex.equals("男")) {
            sex = "1";
        } else if (sex.equals("女")) {
            sex = "2";
        } else {
            sex = "1";
        }
        nickname = update_info_nickname.getText().toString().trim();
        age = update_info_age.getText().toString().trim();
        city = update_info_select_city.getText().toString().trim();
        signature = update_info_avatar.getText().toString().trim();

        if (photoPath != null) {
            fs = new File(photoPath);
        }
        String url = UrlUtil.URL + "/user/modify/info";
        if (fs != null) {

            Map<String, String> map = new HashMap<String, String>();
            if(signature != null){
                if(!signature.equals("")){
                    map.put("signature", signature);
                }
            }
            if(sex != null){
                if(!sex.equals("")){
                    map.put("sex", sex);
                }
            }
            if(nickname != null){
                if(!nickname.equals("")){
                    map.put("nickname", nickname);
                }
            }
            if(age != null){
                if(!age.equals("")){
                    map.put("age", age);
                }
            }
            if(city != null){
                if(!city.equals("")){
                    map.put("city", city);
                }
            }
            OkHttpClient client = new OkHttpClient();
            // form 表单形式上传
            MultipartBody.Builder requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM);
            if(fs != null){
                // MediaType.parse() 里面是上传的文件类型。
                RequestBody body = RequestBody.create(MediaType.parse("image/*"), fs);
                String filename = fs.getName();
                // 参数分别为， 请求key ，文件名称 ， RequestBody
                requestBody.addFormDataPart("avatar", fs.getName(), body);
            }
            if (map != null) {
                // map 里面是请求中所需要的 key 和 value
                for (Map.Entry entry : map.entrySet()) {
                    requestBody.addFormDataPart(String.valueOf(entry.getKey()), String.valueOf(entry.getValue()));
                }
            }
            String sesseionid = new ConnectViaSession(UpdateInfoActivity.this).GetSession();
            okhttp3.Request request = new okhttp3.Request.Builder().url(url).post(requestBody.build()).addHeader("cookie",sesseionid).tag(UpdateInfoActivity.this).build();
            // readTimeout("请求超时时间" , 时间单位);
            client.newBuilder().readTimeout(5000, TimeUnit.MILLISECONDS).build().newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.i("lfq" ,"onFailure");
                }

                @Override
                public void onResponse(Call call, okhttp3.Response response) throws IOException {
                    if (response.isSuccessful()) {
                        String str = response.body().string();
                        Log.i("lfq", response.message() + " , body " + str);
                        try {
                            Map<String, Object> map1 = JsonUtil.jsonToMap(str);
                            Integer code = (Integer) map1.get("code");
                            if (code == 0) {
                                String data = (String) map1.get("data");
                                Toast.makeText(UpdateInfoActivity.this, data, Toast.LENGTH_LONG).show();
                            } else if (code == -1) {
                                Toast.makeText(UpdateInfoActivity.this, "登录失效，请重新登录", Toast.LENGTH_LONG).show();
                                Intent intent = new Intent(UpdateInfoActivity.this, GetPhoneCodeActivity.class);
                                intent.putExtra("loginCode", "-1");
                                startActivity(intent);
                                finish();
                            } else {
                                String data = (String) map1.get("message");
                                Log.i(TAG,data);
                                Toast.makeText(UpdateInfoActivity.this, data, Toast.LENGTH_SHORT).show();
                                overridePendingTransition(R.anim.xpage_slide_in_left, R.anim.xpage_slide_out_right);
                                finish();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    } else {
                        Log.i("lfq" ,response.message() + " error : body " + response.body().string());
                    }
                }
            });
        } else {
            RequestQueue mSingleQueue = Volley.newRequestQueue(UpdateInfoActivity.this);
            StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
                @Override
                public void onResponse(String s) {
                    try {
                        Map<String, Object> map = JsonUtil.jsonToMap(s);
                        Integer code = (Integer) map.get("code");
                        if (code == 0) {
                            String data = (String) map.get("data");
                            Toast.makeText(UpdateInfoActivity.this, data, Toast.LENGTH_LONG).show();

                        } else if (code == -1) {
                            Toast.makeText(UpdateInfoActivity.this, "登录失效，请重新登录", Toast.LENGTH_LONG).show();
                            Intent intent = new Intent(UpdateInfoActivity.this, GetPhoneCodeActivity.class);
                            intent.putExtra("loginCode", "-1");
                            startActivity(intent);
                            finish();
                        } else {
                            String data = (String) map.get("message");
                            Toast.makeText(UpdateInfoActivity.this, data, Toast.LENGTH_SHORT).show();
                            overridePendingTransition(R.anim.xpage_slide_in_left, R.anim.xpage_slide_out_right);
                            finish();
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    Log.e(TAG, volleyError.getMessage(), volleyError);
                }
            }) {
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    String sesseionid = new ConnectViaSession(UpdateInfoActivity.this).GetSession();
                    if (!sesseionid.equals("")) {
                        HashMap<String, String> headers = new HashMap<String, String>();
                        headers.put("cookie", sesseionid);
                        return headers;
                    } else {
                        return super.getHeaders();
                    }
                }
                @Override
                protected Map<String, String> getParams() throws AuthFailureError {
                    Map<String, String> map = new HashMap<String, String>();
                    if(signature != null){
                        if(!signature.equals("")){
                            map.put("signature", signature);
                        }
                    }
                    if(sex != null){
                        if(!sex.equals("")){
                            map.put("sex", sex);
                        }
                    }
                    if(nickname != null){
                        if(!nickname.equals("")){
                            map.put("nickname", nickname);
                        }
                    }
                    if(age != null){
                        if(!age.equals("")){
                            map.put("age", age);
                        }
                    }
                    if(city != null){
                        if(!city.equals("")){
                            map.put("city", city);
                        }
                    }
                    return map;
                }
            };
            mSingleQueue.add(stringRequest);
        }
    }



    /**
     * 返回事件
     */
    private void updateInfoReturn() {
        update_info_return = findViewById(R.id.update_info_return);


        update_info_return.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                overridePendingTransition(R.anim.xpage_slide_in_left, R.anim.xpage_slide_out_right);
                finish();
            }
        });

    }

    /**
     * 修改资料
     */
    private void updateInfoBtn(){
        update_info_btn = findViewById(R.id.update_info_btn);
        update_info_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveUserInfo();
            }
        });
    }

    private void initJsonData() {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new GetJsonDataUtil().getJson(this, "province.json");//获取assets目录下的json文件数据

        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> cityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String cityName = jsonBean.get(i).getCityList().get(c).getName();
                cityList.add(cityName);//添加城市
                ArrayList<String> city_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                /*if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    city_AreaList.add("");
                } else {
                    city_AreaList.addAll(jsonBean.get(i).getCityList().get(c).getArea());
                }*/
                city_AreaList.addAll(jsonBean.get(i).getCityList().get(c).getArea());
                province_AreaList.add(city_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(cityList);

            /**
             * 添加地区数据
             */
            options3Items.add(province_AreaList);
        }

        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);

    }


    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }

    private void showPickerView() {// 弹出选择器

        OptionsPickerView pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public boolean onOptionsSelect(View view, int options1, int options2, int options3) {
                //返回的分别是三个级别的选中位置
                String opt1tx = options1Items.size() > 0 ?
                        options1Items.get(options1).getPickerViewText() : "";

                String opt2tx = options2Items.size() > 0
                        && options2Items.get(options1).size() > 0 ?
                        options2Items.get(options1).get(options2) : "";

                String opt3tx = options2Items.size() > 0
                        && options3Items.get(options1).size() > 0
                        && options3Items.get(options1).get(options2).size() > 0 ?
                        options3Items.get(options1).get(options2).get(options3) : "";

                String tx = opt1tx + opt2tx + opt3tx;
                update_info_select_city.setText(tx);
                return false;
            }
        })

                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .build();

//        pvOptions.setPicker(options1Items);//一级选择器
//        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }


    /**
     * 请求读写SDK权限
     */
    public void chooseUpdatePhoto(View view) {
        if (ContextCompat.checkSelfPermission(UpdateInfoActivity.this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(UpdateInfoActivity.this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_WRITE_EXTERNAL_STORAGE);
        } else {
            openAlbum();
        }
    }

    /**
     * 打开图片浏览器
     */
    private void openAlbum() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");
        startActivityForResult(intent, CHOOSE_PHOTO);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    openAlbum();
                } else {
                    Toast.makeText(this, "拒绝读取SD卡权限将无法获取照片", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case CHOOSE_PHOTO:
                if (resultCode == RESULT_OK) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                        handleImageAfterKitKat(data);
                    } else {
                        handleImage(data);
                    }
                }
                break;
        }
    }

    /**
     * API19之后处理内容
     *
     * @param data onActivityResult 返回结果
     */
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void handleImageAfterKitKat(Intent data) {
        /*ParcelFileDescriptor parcelFileDescriptor =
                null;
        try {
            parcelFileDescriptor = getContentResolver().openFileDescriptor(data.getData(), "r");
            Log.i(TAG, "handleImageAfterKitKat: " + parcelFileDescriptor.toString());
            FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
            Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
            parcelFileDescriptor.close();
            result.setImageBitmap(image);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }*/

        String imagePath = null;
        Uri uri = data.getData();
        Log.i(TAG, uri.toString());
        if (DocumentsContract.isDocumentUri(this, uri)) {
            // 如果是document类型的Uri，通过documentId处理
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docId.split(":")[1];    // 解析出数字格式id
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
                photoPath = imagePath;
            } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
                imagePath = getImagePath(contentUri, null);
                photoPath = imagePath;
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            imagePath = getImagePath(uri, null);
            photoPath = imagePath;
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            imagePath = uri.getPath();
            photoPath = imagePath;
        }
        displayImage(imagePath);
    }

    /**
     * 处理返回结果
     *
     * @param data onActivityResult 返回结果
     */
    private void handleImage(Intent data) {
        Uri uri = data.getData();
        String imagePath = getImagePath(uri, null);
        displayImage(imagePath);
    }

    /**
     * 根据图片路径，显示图片
     */
    private void displayImage(String imagePath) {
        if (imagePath != null) {
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
            Bitmap bitmap1 = CirclePhotoUtil.centerSquareScaleBitmap(bitmap, 100);
            Drawable drawable = new BitmapDrawable(bitmap1);
            update_info_head.setImageDrawable(drawable);
        } else {
            Toast.makeText(this, "照片路径为空", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 使用ContentProvider获取图片路径
     *
     * @param uri       图片uri
     * @param selection 条件
     * @return 图片路径
     */
    private String getImagePath(Uri uri, String selection) {
        String path = null;
        Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }


    /**
     * 输入框监听
     */
    private void UpdateInfoInput() {
        update_info_avatar = findViewById(R.id.update_info_avatar);
        update_info_avaNum = findViewById(R.id.update_info_avaNum);
        update_info_avatar.addTextChangedListener(new TextWatcher() {
            //记录输入的字数
            private CharSequence wordNum;
            private int selectionStart;
            private int selectionEnd;

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                wordNum = s;

            }

            @Override
            public void afterTextChanged(Editable s) {
                int number = num + s.length();
//                TextView显示剩余字数
                update_info_avaNum.setText("" + number + "/80字符");
                selectionStart = update_info_avatar.getSelectionStart();
                selectionEnd = update_info_avatar.getSelectionEnd();
                //判断大于最大值
                if (wordNum.length() > maxNum) {
                    //删除多余输入的字（不会显示出来）
                    s.delete(selectionStart - 1, selectionEnd);
                    int tempSelection = s.length();
                    update_info_avatar.setSelection(tempSelection);//设置光标在最后
                    Toast.makeText(UpdateInfoActivity.this, "最多输入80个字", Toast.LENGTH_SHORT).show();
                }
            }
        });

    }


}
